﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XDFLib.Collections;

namespace NodeBasedSkillEditor.Model.CommandHistory
{
    public class CommandHistory
    {
        public int RecordCount { get { return _records.Count; } }

        public int RecordCapacity {
            get { return _records.Capacity; }
            set { _records.Capacity = Math.Max(value, 1); }
        }

        public int CurrentRecordIndex { get; private set; } = -1;
        public int LoopedRecordIndex => _records.GetLoopedIndex(CurrentRecordIndex);

        Deque<CommandRecord> _records;

        public CommandHistory(int recordCapacity = 100)
        {
            _records = new Deque<CommandRecord>(recordCapacity);
        }

        public void AddRecord(CommandRecord cmdRec)
        {
            if (CurrentRecordIndex < -1)
            {
                var removeFrom = _records.GetLoopedIndex(CurrentRecordIndex + 1);
                _records.RemoveToLast(removeFrom);
                CurrentRecordIndex = -1;
            }

            MakePlaceForAddingRecord();

            _records.AddLast(cmdRec);
        }

        void MakePlaceForAddingRecord()
        {
            if (RecordCount == RecordCapacity)
            {
                _records.RemoveFirst();
            }
        }

        public CommandRecord PreviousRecord()
        {
            CommandRecord result = null;
            if (RecordCount > 0 && CurrentRecordIndex >= -RecordCount)
            {
                result = _records[LoopedRecordIndex];
                CurrentRecordIndex--;
            }

            return result;
        }

        public CommandRecord NextRecord()
        {
            CommandRecord result = null;
            if (RecordCount > 0 && CurrentRecordIndex != -1)
            {
                CurrentRecordIndex++;
                result = _records[LoopedRecordIndex];
            }
            return result;
        }

        public void Clear()
        {
            _records.Clear();
            CurrentRecordIndex = -1;
        }
    }
}
